<?php

namespace app\admin\services;

use app\common\model\Common;
use app\common\services\Service;

class DatabaseService extends Service
{
    protected $model;

    public function __construct()
    {
        $this->model = Common::getInstance();
    }

    /**
     * 获取所有表名
     *
     * @param  bool  $except_monthly_sub_table
     *
     * @return array
     */
    public function getAllTabels(bool $except_monthly_sub_table = false) : array
    {
        $list = [];
        foreach ($this->model->getAllTable() as $table) {
            $table = reset($table);
            // 如果存在年月格式，那么就是按月分表的子表，不展示
            if ( ($except_monthly_sub_table == true && !preg_match("'\d{4}_\d{1,2}'", $table)) || $except_monthly_sub_table == false ) {
                $list[] = (object)$this->model->getTableInfo($table);
            }
        }
        return $list;
    }

    /**
     * 修复指定表
     *
     * @param $table
     *
     * @return bool
     */
    public function setRepair($table) : bool
    {
        if ( $this->model->setRepair($table) ) {
            $this->setError('修复{' . $table . '}成功！');
            return true;
        } else {
            $this->setError('修复{' . $table . '}失败！');
            return false;
        }
    }

    /**
     * 优化指定表
     *
     * @param $table
     *
     * @return bool
     */
    public function setOptimization($table) : bool
    {
        if ( $this->model->setOptimization($table) ) {
            $this->setError('优化{' . $table . '}成功！');
            return true;
        } else {
            $this->setError('优化{' . $table . '}失败！');
            return false;
        }
    }

    /**
     * 批量修复
     *
     * @return bool
     */
    public function setRepairAll() : bool
    {
        $tables = $this->getAllTabels();
        $msg = '';
        $tables_num = count($tables);
        foreach ($tables as $key => $val) {
            $table = reset($val);
            if ( $this->model->setRepair($table) ) {
                $msg .= '修复{' . $table . '}成功' . ($tables_num - 1 == $key ? '！' : '，') . PHP_EOL;
            } else {
                $msg .= '修复{' . $table . '}失败' . ($tables_num - 1 == $key ? '！' : '，') . PHP_EOL;
            }
        }
        $this->setError('批量修复成功！');
        return true;
    }

    /**
     * 批量优化
     *
     * @return bool
     */
    public function setOptimizationAll() : bool
    {
        $tables = $this->getAllTabels();
        $msg = '';
        $tables_num = count($tables);
        foreach ($tables as $key => $val) {
            $table = reset($val);
            if ( $this->model->setOptimization($table) ) {
                $msg .= '优化{' . $table . '}成功' . ($tables_num - 1 == $key ? '！' : '，') . PHP_EOL;
            } else {
                $msg .= '优化{' . $table . '}失败' . ($tables_num - 1 == $key ? '！' : '，') . PHP_EOL;
            }
        }
        $this->setError('批量优化成功！');
        return true;
    }
}